package com.ke.service.impl;

import com.ke.dao.*;
import com.ke.pojo.*;
import com.ke.service.ArticleService;
import com.ke.utils.JwtUtils;
import com.ke.utils.UploadUtil;
import com.ke.utils.UtilTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author bochen
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    ArticleRepository articleRepository;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    ArticleFavorityRepository articleFavorityRepository;

    @Autowired
    ArticleOrderRepository articleOrderRepository;

    @Autowired
    ArticleCommentRepository articleCommentRepository;

    @Override
    public BaseResp findArticleByTime(int size) {
        List<Article> list=articleMapper.findArticleByTime(size);
        return new BaseResp(0,"查询成功",list);
    }

    @Override
    public BaseResp findAll(Integer page, Integer size) {
        PageRequest of = PageRequest.of(page-1, size);
        Page<Article> all = articleRepository.findAll(of);
        List<Article> list= all.getContent();
        for(Article article:list){
            if(article.getAddress()== null || article.getAddress() == ""){
                continue;
            }
            Long address = Long.parseLong(article.getAddress());
            ArticleMongoDB articleMongoDB = mongoTemplate.findById(address, ArticleMongoDB.class);
            if(articleMongoDB==null){
                continue;
            }
            article.setContent(articleMongoDB.getText());
        }
        return new BaseResp(0,"查询成功",list,all.getTotalElements());
    }

    /**
     * 适用于不知用户是否登录的情况
     * @param id
     * @return
     */
    @Override
    public BaseResp findById(Integer id) {
        Optional<Article> byId = articleRepository.findById(id);
        //判断是否能够查询到该文章
        if (byId == null) {
            return new BaseResp(1, "查询失败");
        }

        //获取article对象
        Article article = byId.get();
        //判断文章价格是否大于0,大于零则不显示文章内容
        if(article.getPrice()>0){
            article.setContent("");
            return new BaseResp(0, "该文章为付费内容!请先付费在查看!", article);
        }
        //通过address唯一表示从mongoDB中获取ArticleMongoDB对象
        Long address = Long.parseLong(article.getAddress());
        if(address==null){
            return new BaseResp(0, "查询成功", article);
        }
        ArticleMongoDB articleMongoDB = mongoTemplate.findById(address, ArticleMongoDB.class);
        if(articleMongoDB==null){
            return new BaseResp(0, "查询成功", article);
        }
        //将文章的内容赋值给article
        article.setContent(articleMongoDB.getText());
        return new BaseResp(0, "查询成功", article);
    }

    /**
     * 适用于不知用户是否登录的情况
     * @param id
     * @return
     */
    @Override
    public BaseResp findByIdUserLogin(Integer id,HttpServletRequest request) {
        //获取用户id,并设置uid的值
        Integer uid= new Integer(request.getAttribute("id").toString());
        Optional<Article> byId = articleRepository.findById(id);
        //判断是否能够查询到该文章
        if (byId == null) {
            return new BaseResp(1, "查询失败");
        }
        //获取article对象
        Article article = byId.get();
        //判断文章价格是否大于0,并且判断用户是否未已支付
        //首先从订单中查询用户是否存在该订单
        ArticleOrder articleOrder =null;
        if(article.getPrice()>0){
            //价格大于0
            List<ArticleOrder> byUserId = articleOrderRepository.findByUserId(uid);
            //判断该用户是否有订单
            if(byUserId==null) {
                article.setContent("");
                return new BaseResp(0, "该文章为付费内容!请先付费在查看!", article);
            }

            for(ArticleOrder artOrder :byUserId){
                //判断该用户是否存在该文章的订单
                if(artOrder.getArticleId()==id){
                    articleOrder=artOrder;
                    //如果存在,判断订单的状态是否已支付,未支付则返回
                    if(!articleOrder.getStatus().equals("TRADE_SUCCESS")){
                        return new BaseResp(1,"文章未付费!请先支付!");
                    }
                }
            }

            //如果该用户没有该文章得订单,则直接返回
            if(articleOrder==null){
                article.setContent("");
                return new BaseResp(0, "该文章为付费内容!请先付费在查看!", article);
            }
        }
        //通过address唯一表示从mongoDB中获取ArticleMongoDB对象
        Long address = Long.parseLong(article.getAddress());
        if(address==null){
            return new BaseResp(0, "查询成功", article);
        }
        ArticleMongoDB articleMongoDB = mongoTemplate.findById(address, ArticleMongoDB.class);
        if(articleMongoDB==null){
            return new BaseResp(0, "查询成功", article);
        }
        //将文章的内容赋值给article
        article.setContent(articleMongoDB.getText());
        return new BaseResp(0, "查询成功", article);
    }



    @Override
    public BaseResp updateOrInsert(Article article, HttpServletRequest request) {

        try {
            //获取文章的文本内容,将其存放到mongoDB数据库中
            ArticleMongoDB articleMongoDB = new ArticleMongoDB();
            //生成唯一表示,19位的数字字符串
            String num = UtilTools.getNum();
            articleMongoDB.setId(Long.parseLong(num));
            articleMongoDB.setText(article.getContent());
            mongoTemplate.save(articleMongoDB);

            //同时将唯一标识保存在文章的address中
            article.setAddress(num);
            //设置文章的属性
            article.setCreateTime(new Date());
            article.setCollectNumber(0);
            article.setLikeNumber(0);
            article.setCid(1);
            //获取用户id,并设置uid的值
            Integer uid= new Integer(request.getAttribute("id").toString());
            article.setUid(uid);
            Article article1 = articleRepository.saveAndFlush(article);
            return new BaseResp(0,"成功",article1);
        }catch (Exception e){
            return new BaseResp(1,"失败");
        }
    }

    /**
     * 上传文章的插图
     * @param aticleInsertPic
     * @return
     */
    @Override
    public Map upload(AticleInsertPic aticleInsertPic) {
        MultipartFile img = aticleInsertPic.getImg();
        String s = UploadUtil.upload(img);
        Map map = new HashMap();
        map.put("code",200);
        map.put("url",s);
        return map;
    }

    /**
     * 通过文章id增加点赞数
     * @param id
     * @return
     */
    @Override
    public BaseResp addLikeNumber(Integer id) {
        int flag = articleMapper.addLikeNumber(id);
        Optional<Article> byId = articleRepository.findById(id);
        Article article = byId.get();
        if(flag>0){
            //修改成功
            return new BaseResp(0,"增加成功",article.getLikeNumber());
        }else{
            return new BaseResp(1,"增加失败");
        }
    }

    /**
     * 添加收藏夹
     * @param id
     * @return
     */
    @Override
    public BaseResp addFactority(Integer id,HttpServletRequest request) {
        //获取用户id,并设置uid的值
        Integer uid= new Integer(request.getAttribute("id").toString());
        String username = request.getAttribute("username").toString();
        Optional<Article> byId = articleRepository.findById(id);
        Article article = byId.get();
        Favority favority = new Favority();
        favority.setArticleId(id);
        favority.setUserId(uid);
        favority.setCreateTime(new Date());
        favority.setUserName(username);
        favority.setArticleName(article.getArticleName());
        favority.setCollectNumber(article.getCollectNumber());
        favority.setPic(article.getPic());
        favority.setPrice(article.getPrice());
        favority.setLikeNumber(article.getLikeNumber());
        articleFavorityRepository.save(favority);
        return new BaseResp(0,"添加收藏成功!");
    }

    /**
     * 验证用户是否已收藏该文章
     * @param id
     * @param request
     * @return
     */
    @Override
    public BaseResp verifyFactority(Integer id, HttpServletRequest request) {
        //获取用户id,并设置uid的值
        Integer uid= new Integer(request.getAttribute("id").toString());
        List<Favority> list = articleFavorityRepository.findByUserId(uid);
        for(Favority favority :list){
            if(id==favority.getArticleId()){
                return new BaseResp(0,"用户已收藏");
            }
        }
        return new BaseResp(1,"用户未收藏");
    }

    /**
     * 查询全部收藏夹
     * @param request
     * @return
     */
    @Override
    public BaseResp findAllFavorites(HttpServletRequest request) {
        //获取用户id,并设置uid的值
        Integer uid= new Integer(request.getAttribute("id").toString());
        List<Favority> list = articleFavorityRepository.findByUserId(uid);
        return new BaseResp(0,"查询成功",list);
    }

    /**
     * 删除收藏夹文章
     * @param id
     * @return
     */
    @Override
    public BaseResp deleteFavorityArticleById(Integer id) {
        articleFavorityRepository.deleteById(id);
        return new BaseResp(0,"删除成功!!");
    }

    /**
     * 评价文章
     * @param articleComment
     * @param request
     * @return
     */
    @Override
    public BaseResp addArticleCommend(ArticleComment articleComment, HttpServletRequest request) {
        String username = request.getAttribute("username").toString();
        articleComment.setUserName(username);
        articleComment.setCreateTime(new Date());
        ArticleComment save = articleCommentRepository.save(articleComment);
        if(save!=null){
            return new BaseResp(0,"评论成功");
        }else{
            return new BaseResp(0,"评论失败");
        }

    }

    /**
     * 查询文章评论
     * @param id
     * @return
     */
    @Override
    public BaseResp findAllArticleCommend(Integer id) {
        List<ArticleComment> list = articleCommentRepository.findByArticleId(id);
        if(list!=null){
            return new BaseResp(0,"查询成功",list);
        }else{
            return new BaseResp(0,"评论为空");
        }


    }
}
